
package com.scalar.chiptrack.operations.packingslip.jobs;

import java.util.Calendar;
import java.util.ArrayList;
import java.util.Iterator;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.utils.Mailer;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.sales.dao.SalesDAO;
import com.scalar.chiptrack.sales.LineItem;


public class PackingSlipReminderJob extends JobHandler {

    
    private static final String EMAIL_SEPARATOR = ",";
    private static final String PACKING_SLIP_VIEW_URI = "/packingSlip.do?action=loadSalesOrder&salesOrderId=";
    private static final String USER_PROFILE_URI = "userProfile.do";
    
    private Calendar m_shipDate = null;
    
    public PackingSlipReminderJob() {
        m_shipDate = Calendar.getInstance();
    }
    
    public void execute() throws Exception {

        ArrayList shippedLineItemList = null;
        ArrayList userList = null;
        
        try {
            userList = UserDAO.loadUsersWithModifyFunctionAccess (Functionality.ORDER_SCHEDULING);
            if ((userList == null) || (userList.size() == 0)) {
                return;
            }
            //System.out.println ("number of users = " + userList.size());
            
            m_shipDate.add (Calendar.DAY_OF_MONTH, ConfigManager.getPackingSlipReminderDays());
            java.sql.Date date = new java.sql.Date (m_shipDate.getTimeInMillis());

            shippedLineItemList = SalesDAO.loadAllShippableLineItemsByDate (date.toString());
            if ((shippedLineItemList == null) || (shippedLineItemList.size() == 0)) {
                return;
            }

            //System.out.println ("number of Shippable orders = " + shippedLineItemList.size());
            sendAlert (shippedLineItemList, userList);
        }
        catch (Exception e) {
            System.err.println ("Exception while running PackingSlipReminderJob: " + e);
            e.printStackTrace();
            throw e;
        }
    }


    private void sendAlert (ArrayList shippedLineItemList, ArrayList userList) throws Exception {

        Iterator users = userList.iterator();
        User user = null;
        String email = null;
        StringBuffer emails = new StringBuffer();

        while (users.hasNext()) {
            user = (User) users.next();
            email = user.getEmail();

            if (email != null) {
                emails.append (email).append (Mailer.EMAIL_SEPARATOR);
            }
        }

        String bcc = emails.toString();
        if ((bcc == null) || (bcc.trim().length() == 0)) {
            return;
        }
        bcc = bcc.substring(0, (bcc.length()-1));

        String from = ConfigManager.getSysAdminEmail();
        String to = ConfigManager.getSysAdminEmail();
        
        String subject = "Sales Orders ready to be shipped on " + (m_shipDate.get (Calendar.MONTH) + 1) + "/" + m_shipDate.get (Calendar.DAY_OF_MONTH) + "/" + m_shipDate.get (Calendar.YEAR);
        String message = createMessageBody (shippedLineItemList);

        Mailer.send (from, to, null /*cc*/, bcc, subject, message, null /*fileAttachments*/, Mailer.CONTENT_TYPE_HTML);

    }

    
    private String createMessageBody (ArrayList shippedLineItemList) {    
        
        Iterator shippedLineItems = shippedLineItemList.iterator();
        LineItem lineItem = null;
        
        StringBuffer messageBody = new StringBuffer();
        int i=0;
        String bgColor = null;
        
        messageBody.append ("<html><body bgcolor='FDF5E6'>");
        messageBody.append ("<h2><u>Sales Orders ready to be shipped on " + (m_shipDate.get (Calendar.MONTH) + 1) + "/" + m_shipDate.get (Calendar.DAY_OF_MONTH) + "/" + m_shipDate.get (Calendar.YEAR));
        messageBody.append ("<p><table border='0' bgcolor='#FFFFFF'><tr>");
        messageBody.append ("<td width='10%' align='center' bgcolor='#993333'><font color='#FFFFFF'>Sales Order Number</font></td>");
        messageBody.append ("<td width='10%' align='center' bgcolor='#993333'><font color='#FFFFFF'>Line Item No</td>");
        messageBody.append ("<td width='10%' align='center' bgcolor='#993333'><font color='#FFFFFF'>Mkt Part No</td>");
        messageBody.append ("<td width='10%' align='center' bgcolor='#993333'><font color='#FFFFFF'>Customer Req Qty</td>");
        messageBody.append ("<td width='10%' align='center' bgcolor='#993333'><font color='#FFFFFF'>Unit Price</td>");
        messageBody.append ("<td width='10%' align='center' bgcolor='#993333'><font color='#FFFFFF'>Amount</td>");
        messageBody.append ("<td width='10%' align='center' bgcolor='#993333'><font color='#FFFFFF'>Booking Date</td>");
        messageBody.append ("<td width='10%' align='center' bgcolor='#993333'><font color='#FFFFFF'>Requested Date</td>");
        messageBody.append ("<td width='10%' align='center' bgcolor='#993333'><font color='#FFFFFF'>Schedule Date</td>");
        messageBody.append ("<td width='10%' align='center' bgcolor='#993333'><font color='#FFFFFF'>Revised Date</td></tr>");
        
        while (shippedLineItems.hasNext()) {
            
            if (i%2 == 0) bgColor = "#FFFFFF";
            else bgColor = "#DEE1E2";

            lineItem = (LineItem) shippedLineItems.next();            
            messageBody.append ("<tr>");
            messageBody.append ("<td bgColor='" + bgColor + "' align='center' width='10%'>");
            messageBody.append ("<a href='http://").append (ConfigManager.getChipTracHost()).append ("/").append (ConfigManager.getChipTracContext()).append (PACKING_SLIP_VIEW_URI).append (lineItem.getSalesOrderId()).append ("'>");
            messageBody.append (lineItem.getSalesOrderNo()).append ("</a>");
            messageBody.append ("</td><td bgColor='" + bgColor + "' align='center' width='10%'>").append (lineItem.getLineItemNo());
            messageBody.append ("</td><td bgColor='" + bgColor + "' align='center' width='10%'>").append (lineItem.getMarketingPartNo());
            messageBody.append ("</td><td bgColor='" + bgColor + "' align='right'  width='10%'>").append (StringUtils.formatUnits(lineItem.getQuantity()));
            messageBody.append ("</td><td bgColor='" + bgColor + "' align='right'  width='10%'>").append ("$").append (StringUtils.formatAmount(lineItem.getUnitPrice(), null));
            messageBody.append ("</td><td bgColor='" + bgColor + "' align='right'  width='10%'>").append ("$").append (StringUtils.formatAmount(lineItem.getAmount(), null));
            messageBody.append ("</td><td bgColor='" + bgColor + "' align='center' width='10%'>").append (lineItem.getBookingDate());
            messageBody.append ("</td><td bgColor='" + bgColor + "' align='center' width='10%'>").append (lineItem.getRequestDate());
            messageBody.append ("</td><td bgColor='" + bgColor + "' align='center' width='10%'>").append (lineItem.getScheduleDate());
            messageBody.append ("</td><td bgColor='" + bgColor + "' align='center' width='10%'>");
            
            if (lineItem.getRevisedDate() != null) {
                messageBody.append (lineItem.getRevisedDate());
            }
            else {
                messageBody.append ("&nbsp");
            }
            messageBody.append ("</td></tr>");
            
            i++;
        }

        messageBody.append ("</table>");

        // Footer - start
        messageBody.append ("<br><br><br><br><table width='60%' border='0'>");        
        messageBody.append ("<tr><td>___________________________________________________________</td></tr>");
        messageBody.append ("<tr><td><font size=2>You are receiving this email because you have the access rights to generate</font></td></tr>");
        messageBody.append ("<tr><td><font size=2>a packing slip from ChipTrac System. If you no longer wish you receive this email</font></td></tr>");
        messageBody.append ("<tr><td><font size=2>Please contact your system administrator.</font></td></tr></table>");
        // Footer - End

        messageBody.append ("<br><br><br><br></body></html>");

        
        return messageBody.toString();
    }

    
    public static void main (String[] args) throws Exception {
        new PackingSlipReminderJob().execute();
    }
}